

import org.fusesource.jansi.AnsiConsole;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.*;

import static org.fusesource.jansi.Ansi.Color.*;
import static org.fusesource.jansi.Ansi.ansi;

public class JavaSrverConnectTest {
//    private List<String> str=new ArrayList<>();
    private List<ReadJsonFile.Json> json = new ArrayList<>();
    //连接服务器
    private void jsc(ReadJsonFile.Json json){
        try {
            URL url1 = new URL("http://"+json.getIP());
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
            // 设置请求方法为GET
            connection.setRequestMethod("GET");
            // 获取开始时间
            long startTime = System.currentTimeMillis();
            // 获取响应代码
            int responseCode = connection.getResponseCode();
            // 获取结束时间
            long endTime = System.currentTimeMillis();

            // 计算响应时间
            long responseTime = endTime - startTime;
            //
            Maps maps = new Maps();
            String s = maps.in().get(responseCode);
            //
            URL url2= connection.getURL();

            //转固定格式
            String urladdress = String.format("%-25s",json.getIP());
            if (responseCode == 200) {
//                System.out.print(urladdress + "文件接收服务正常！ \t");
                AnsiConsole.systemInstall();
                System.out.print(urladdress + ansi().fg(GREEN).a("文件接收服务正常！ \t").reset());
                System.out.print(responseCode + "\t" + s + "\t");
                System.out.printf(" ( %.2f sec )\t", ((double) responseTime / 1000));
                //同步文件
                System.out.println("开始同步文件");
                SFTPSender sftpSender = new SFTPSender(json.getIP(),json.getUsername(),json.getPassword(),json.getFile());
                sftpSender.serverSFTPConnection();
                //每行输出到文件log.txt并输出系统时间
                try (FileWriter fileWriter = new FileWriter("log.txt",true);
                     BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
                    bufferedWriter.write(urladdress + "文件接收服务正常！\t"+System.currentTimeMillis()+"\n");
                } catch (IOException ioException) {
                    System.err.println("文件写入错误！"+ioException.getMessage());
                }
            } else {
//                System.err.print(urladdress + " 文件接收服务异常！\t");
                System.out.print(urladdress + ansi().fg(RED).a("文件接收服务异常！\t").reset());
                System.out.print(responseCode + "\t" + s + "\t");
                System.out.printf(" ( %.2f sec )\t", ((double) responseTime / 1000));
            }

            // 关闭连接
            connection.disconnect();
        } catch (Exception e) {
            String urladdress = String.format("%-25s",json.getIP());
//            System.out.print(urladdress+" 服务器连接失败！"+e.getMessage()+"\t连接超时！\t");
            System.out.print(urladdress+ansi().fg(RED).a(" 服务器连接失败！").reset()+ansi().fg(RED).a(e.getMessage()).reset()+ansi().fg(RED).a("\t连接超时！\t").reset());
            //每行输出到文件a.txt并输出系统时间
            try (FileWriter fileWriter = new FileWriter("log.txt",true);
                 BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
                bufferedWriter.write(urladdress+" 服务器连接失败！"+e.getMessage()+"\t连接超时！\t"+System.currentTimeMillis()+"\n");
            } catch (IOException ioException) {
                System.err.println("文件写入错误！"+ioException.getMessage());
            }
        }
    }
    //读取服务器列表文件
    private List<String> readerServerList(String fileAddress){
        List<String> res = new ArrayList<>();
        try(FileReader fileReader = new FileReader(fileAddress);
            BufferedReader bufferedReader = new BufferedReader(fileReader)){
            String str ="";
            while((str=bufferedReader.readLine())!=null) res.add(str);
        } catch (IOException e) {
            System.err.println("文件读取错误！"+e.getMessage());
        }
        return res;
    }
    //线程池
    private ThreadPoolExecutor threadPoolExecutor(){
     return new ThreadPoolExecutor(
            3,
            5,
            60,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(3)
    );
}
    //运行代码
    public void open(){
        Scanner sc = new Scanner(System.in );
        System.out.println("请输入服务器列表文件及路径：");
        String serverListAddress=sc.nextLine();
        File file = new File(serverListAddress);
        if(!file.isFile()){
            while(true){
                System.out.println("路径错误！");
                System.out.println("请重新输入服务器列表文件及路径：");
                serverListAddress=sc.nextLine();
                file = new File(serverListAddress);
                if(file.isFile()){
                    break;
                }
            }
        }
        System.out.println("******************************************开始执行***********************************************");
        System.out.println("*******"+"服务器名"+"******\t"+"    ***"+"接收是否正常"+"*** \t"+"*******"+"状态码"+"********"+"**"+"执行时间"+"**\t"+"**"+"文件同步状态"+"**"+"执行线程"+"****");
        System.out.println();

        json = ReadJsonFile.readJson(file);
        ThreadPoolExecutor threadPoolExecutor = threadPoolExecutor();
        JavaSrverConnectTest jscTest = new JavaSrverConnectTest();
//        String finalServerListAddress = serverListAddress;

//        ThreadPoolExecutor executor = threadPoolExecutor();
//        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
//        String finalServerListAddress1 = serverListAddress;
//        scheduler.scheduleAtFixedRate(() -> {
//            executor.submit(new Runnable() {
//                @Override
//                public void run() {
//                    json = ReadJsonFile.readJson(finalServerListAddress1);
////                    str=jscTest.readerServerList(finalServerListAddress);
//                    if(json.isEmpty()){
//                        AnsiConsole.systemInstall();
//                        System.out.println(ansi().fg(RED).a("文件为空！").reset());
//                        System.exit(1);
//                    }
//                }
//            });
//        }, 0, 1, TimeUnit.SECONDS);
        while(true) {

            for (int i = 0; i < json.size(); i++) {
                int finalI = i;
                threadPoolExecutor.execute(new Runnable() {
                    @Override
                    public void run() {

//                        for (int i = 0; i < json.size(); i++) {
                        jscTest.jsc(json.get(finalI));
//                        jscTest.jsc(str.get(finalI));
                        System.out.println(Thread.currentThread().getName() + "\n");
                        //输出到文件a.txt并输出系统时间
                        try (FileWriter fileWriter = new FileWriter("log.txt", true);
                             BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
                            bufferedWriter.write(Thread.currentThread().getName() + "\n");
                        } catch (IOException ioException) {
                            System.out.println("文件写入错误！" + ioException.getMessage());
                        }
//                        }
//                        try {
//                            Thread.sleep(2000);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//
                    }

                });
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}



